<?php

namespace App\Jobs\Zhunya;

use App\Models\CacheModel\UserCoupon;
use App\Models\CacheModel\ZhunleGroupRecallCampaign;
use App\Models\CacheModel\ZhunleGroupUserRecallRecord;
use App\Models\CacheModel\ZlCouponAttr;
use App\Models\Api\Goods;
use App\Models\Api\MessageCenter;
use App\Models\Api\User;
use Cache;
use Log;

use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;

class NewUserRegisterPackageSendJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public $jobData;

    /**
     * Create a new job instance.
     *
     * @param array $jobData
     */
    public function __construct(array $jobData)
    {
        $this->jobData = $jobData;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function task()
    {
      $jobData = $this->jobData;
       /**
         *     "jobData": {
         * "id": 1,    // recall_record_id  召回记录ID
         * "cids": "20",
         * "coupon_expire_time": 7,
         * "acid": 1,  // campaign_id 召回活动ID
         * "uids": [
         * 11062203,
         * 11290531,
         * 15283829,
         * 15374292,
         * 17026341,
         * 17038299,
         * 17133940,
         * 17253756
         * ]
         * },
         */
        $jobAttempts = $job->attempts();
        if ($jobAttempts > 1)
        {
            $job->delete();
        }
        Log::write('分群召回:推送数据开始' . json_encode($jobData, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), 'log', true);

        $userRecallRecordModel = new ZhunleGroupUserRecallRecord();
        // 获取未发送召回状态用户 以防重复处理
        $userRecallRecordUserList = $userRecallRecordModel->where('campaign_id', $jobData['acid'])
            ->where('recall_record_id', $jobData['id'])
            ->where('is_send', 0)
            ->whereIn('uid', $jobData['uids'])
            ->field('id,uid')
            ->select();

        if ($userRecallRecordUserList)
        {
            $couponInfos = null;
            $sucUserNum = 0; // 发送召回信息成功用户数量
            // 获取活动信息
            $activeInfo = (new ZhunleGroupRecallCampaign())->where('id', $jobData['acid'])->find();
            $userCouponModel = new UserCoupon();
            if ($activeInfo)
            {
                $link = str_replace('[record_id]', $jobData['id'], $activeInfo['link']);
                foreach ($userRecallRecordUserList as $userRecallRecordUserItem)
                {
                    try
                    {
                        $smsIsSend = 0;
                        $time = time();
                        if ((int)$activeInfo['type'] === 1)
                        {   // 推送
                            // PUSH推送
                            (new Push())->pushUserMsg($userRecallRecordUserItem['uid'], $activeInfo['content'], ['target' => $activeInfo['target'], 'link' => $link, 'action' => 'extend']);
                        } else
                        {   // 短信
                            // 获取用户手机号
                            $userInfo = (new User())->getUserinfo(['id' => $userRecallRecordUserItem['uid']]);
                            $tel = $userInfo['tel'] ?? '';
                            if ($tel)
                            {
                                $res = Util::sendYxSms([$tel], '', $activeInfo['msg_template_id'], []);
                                if ($res['success'] && isset($res['data']['code']) && $res['data']['code'] == 200)
                                {
                                    $smsIsSend = 1;
                                }
                                Log::write("分群召回:短信发送手机号：$tel 结果" . json_encode($res, JSON_UNESCAPED_UNICODE), 'log', true);
                            }
                        }

                        if ((int)$activeInfo['send_app_msg'] === 1)
                        {   // 发送站内信
                            // 消息中心添加信息
                            $messageData = [
                                'status' => 0,
                                'is_read' => 0,
                                'range' => $userRecallRecordUserItem['uid'],
                                'type' => 2,
                                'reid' => 0,
                                'cid' => 0,// 默认消息
                                'title' => $activeInfo['app_msg_title'],
                                'content' => $activeInfo['content'],
                                'link' => $link,
                                'target' => $activeInfo['target'],
                                'create_time' => time()
                            ];
                            //添加消息
                            (new MessageCenter())->pushMessage($userRecallRecordUserItem['uid'], $messageData);
                        }

                        if ($jobData['is_send_coupon'] == 2 && $jobData['cids'])
                        {   // 发送优惠券
                            if (is_null($couponInfos))
                            {
                                $couponInfos = (new ZlCouponAttr())->field('id,name,desc,type,gids,ur_id')->whereIn('id', $jobData['cids'])->select();
                            }

                            if ($couponInfos)
                            {
                                foreach ($couponInfos as $k => $couponInfoItem)
                                {
                                    $cData = [
                                        'uid' => $userRecallRecordUserItem['uid'],
                                        'c_id' => $couponInfoItem['id'],
                                        'ur_id' => $couponInfoItem['ur_id'],
                                        'start_time' => $time,
                                        'end_time' => strtotime("+{$jobData['coupon_expire_time']} day", $time),
                                        'give_time' => $time,
                                        'status' => 0,
                                        'price' => 0,
                                        'is_give' => 0,
                                        'create_time' => $time,
                                        'update_time' => 0,
                                    ];

                                    // 写入用户卡券中心
                                    $ucId = $userCouponModel->insertGetId($cData);
                                    // 更新用户卡券中心缓存
                                    $userCouponModel->listDataAdd($userRecallRecordUserItem['uid'], [$ucId => $ucId], 1);

                                    $userRecallRecordUserItem->is_receive_coupon = 1;
                                    $userRecallRecordUserItem->receive_time = $time;

                                    if (!isset($couponInfoItem['couponRangeArr']))
                                    {
                                        // 神策打点
                                        $gidsArr = explode(',', $couponInfoItem['gids']);
                                        $couponInfoItem['couponRangeArr'] = (new Goods())->where('id', 'in', $gidsArr)->column('name');
                                        $couponInfos[$k]['couponRangeArr'] = $couponInfoItem['couponRangeArr'];
                                    }
                                    // 神策打点 75 获得优惠券 AcquireCoupon
                                    SensorsData::track($userRecallRecordUserItem['uid'], true, 'AcquireCoupon', [
                                        'refer_name' => '',
                                        'refer_link' => '',
                                        'coupon_name' => $couponInfoItem['desc'],
                                        'coupon_expire' => date('Y-m-d H:i:s', $cData['end_time']),
                                        'coupon_type' => $this->couponTypeName[$couponInfoItem['type']],
                                        'coupon_range' => $couponInfoItem['couponRangeArr'],
                                        'acquire_channel' => "神策分群召回【{$jobData['id']}】",
                                        'is_give' => false,
                                        'acquire_scene' => '系统赠送',
                                    ]);
                                }
                            } else
                            {
                                Log::write('分群召回->优惠券赠送失败：【' . json_encode(['id' => $jobData['id'], 'cids' => $jobData['cids'], 'coupon_expire_time' => $jobData['coupon_expire_time'], 'acid' => $jobData['acid']], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . "】uid:{$userRecallRecordUserItem['uid']}错误消息：优惠券信息获取失败", 'error', true);
                            }
                        }

                        $userRecallRecordUserItem->is_send = 1;
                        $userRecallRecordUserItem->sms_is_send = $smsIsSend;
                        $userRecallRecordUserItem->send_time = $time;
                        $userRecallRecordUserItem->save();
                        $sucUserNum++;
                    }
                    catch (\Exception $e)
                    {
                        Log::write('分群召回信息发送失败：【' . json_encode(['id' => $jobData['id'], 'cids' => $jobData['cids'], 'coupon_expire_time' => $jobData['coupon_expire_time'], 'acid' => $jobData['acid']], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . "】uid:{$userRecallRecordUserItem['uid']}错误消息：「{$e->getMessage()}」,文件：{$e->getFile()},行数：{$e->getLine()}", 'error', true);
                    }
                    usleep(10);
                }

                $totalUid = count($jobData['uids']);
                Log::write('分群召回:推送数据结束' . json_encode($jobData, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . '此次发送召回用户总数' . $totalUid . ';其中之前已经发送过召回信息用户数：' . ($totalUid - count($userRecallRecordUserList)) . ";本次发送召回成功用户数:{$sucUserNum}", 'log', true);
            } else
            {   // 召回活动信息异常 未找到召回活动信息
                Log::write('分群召回：【' . json_encode($jobData, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . "】错误消息：获取召回活动信息失败", 'error', true);
            }
        } else
        {   // 全部处理完成 没有需要发送召回的用户
            Log::write('分群召回：【' . json_encode($jobData, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . "】错误消息：所有用户都已经推送过召回信息", 'error', true);
        }

        $job->delete();
    }

}
